package com.danbay.framework.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * Created by SJG on 2017/9/29.
 */
public class HttpUtils {

    private static final Logger logger= LoggerFactory.getLogger(HttpUtils.class);


    /**
     * post提交数据
     * @param url 地址
     * @param onSuccess 成功回调
     * @param onFail 失败回调
     * @param keyValues 要提交的数据
     */
    public static <T> void post(String url, Consumer<T> onSuccess, Consumer<IOException> onFail, Object ...keyValues){
        //构造http客户端
        OkHttpClient.Builder clientBuilder=new OkHttpClient.Builder();
        OkHttpClient client =clientBuilder
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .build();

        //构造请求体
        FormBody.Builder bodyBuilder= new FormBody.Builder();
        for(int i=0;i<keyValues.length-1;i+=2){
            if(keyValues[i]==null){
                continue;
            }
            Object value=keyValues[i+1];
            bodyBuilder.add(keyValues[i].toString(),value==null?"":value.toString());
        }
        RequestBody formBody = bodyBuilder.build();

        //构造请求
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                if(onFail!=null) {
                    onFail.accept(e);
                }
                logger.debug("post failed!",e);
            }

            public void onResponse(Call call, Response response) throws IOException {
                Object result=null;
                try {
                    //将json转换为map
                    result = translateResponse(response);
                }catch (IOException e){
                    if(onFail!=null){
                        onFail.accept(e);
                    }
                }
                //如果转换失败
                if(onSuccess!=null) {
                    T t =null;
                    try {
                        //防止返回数据类型与预期不符，转换出错
                        t=(T) result;
                    }catch (Exception e){
                        logger.error(url+" response error data: "+ Arrays.toString(keyValues));
                    }
                    onSuccess.accept(t);
                }
            }

        });
    }

    /**
     * post提交数据
     * @param url 地址
     * @param onSuccess 成功回调
     * @param keyValues 要提交的数据
     */
    public static <T> void post(String url, Consumer<T> onSuccess, Object ...keyValues){
        post(url,onSuccess,null,keyValues);
    }


    /**
     * post提交数据
     * @param url 地址
     * @param keyValues 要提交的数据
     */
    public static void post(String url, Object ...keyValues){
        post(url,null,null,keyValues);
    }

    /**
     * 处理响应内容
     * @param response
     * @return
     */
    private static Object translateResponse(Response response) throws IOException {
        String str = response.body().string();
        Object result=str;
        //判断返回内容是否为json
        if(str.startsWith("{") && str.endsWith("}")){
            //转换为map
            result = new ObjectMapper().readValue(str, Map.class);
        }
        return result;
    }
}
